import Vue from "vue";
import Vuex from "vuex";
import { initState, initStorage, getters } from "./state";
import actions from "./actions";
import modules from "./modules";

Vue.use(Vuex);

const $vue = Vue.prototype;

export const SET_DATA = "setData";
export const getStore = (key, defVal = null) => {
  let val = defVal;
  try {
    val = uni.getStorageSync(key);
    if (val === "") val = defVal;
  } catch (e) {
    //
  }
  return val;
};
$vue.$getStore = getStore;

export const setState = (data) => {
  store.commit(SET_DATA, data);
};
$vue.$setState = setState;

export const setStore = (key, val) => {
  if (typeof key == "object") {
    for (const k in key) {
      setStore(k, key[k]);
    }
    return key;
  }
  try {
    uni.setStorageSync(key, val);
    if (key in store.state) {
      setState({
        [key]: val,
      });
    }
  } catch (e) {
    console.log("set-store-err", e);
  }
};
$vue.$setStore = setStore;
uni.setStore = setStore;

export const clearStore = function () {
  uni.clearStorageSync();
  setStore(initStorage);
};
$vue.$clearStore = clearStore;

// const [clearKey, clearVal] = ["clear-key", "1.3.9"];
// if (getStore(clearKey) != clearVal) {
//   clearStore();
//   setStore(clearKey, clearVal);
// }

const state = {
  ...initState,
};

for (const key in initStorage) {
  const defval = initStorage[key];
  state[key] = getStore(key, defval);
}
// console.log(state);

const store = new Vuex.Store({
  state,
  modules,
  mutations: {
    [SET_DATA](state, data) {
      for (const key in data) {
        state[key] = data[key];
      }
    },
  },
  getters,
  actions: {
    setStore(_, data) {
      return setStore(data);
    },
    ...actions,
  },
});

export default store;

const getSysInfo = () => {
  uni.getSystemInfo({
    success(sysInfo) {
      sysInfo.inSdk = /sdk/i.test(sysInfo.hostName);
      console.log(sysInfo);
      setState({
        sysInfo,
        isDark: (sysInfo.theme || sysInfo.hostTheme) == "dark",
      });
      setSize(sysInfo);
    },
  });
};
$vue.$getSysInfo = getSysInfo;
getSysInfo();

$vue.$setMsg = () => {
  uni.$u.toast("请用uni.$emit / uni.$on");
};

function setSize({ windowWidth, windowHeight }) {
  setState({
    windowWidth,
    windowHeight,
  });
  // console.log(windowWidth, windowHeight);
}
// 如App端设置软键盘弹出方式为adjustResize ，则在键盘弹出时，会触发此事件。
// 横竖屏切换时，会触发此事件。
// uni.onWindowResize((res) => {
//   setSize(res.size);
// });

setInterval(() => {
  setState({
    nowDate: new Date(),
  });
}, 1e3);

// #ifdef H5
window.onblur = () => {
  setState({
    isFocus: false,
  });
};
window.onfocus = () => {
  setState({
    isFocus: true,
  });
};
// #endif
